package hi;


import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

public class KeyController implements KeyListener {

	private boolean appVisible = true;
	
	private List<BooleanListener> mouseActiveListeners = new ArrayList<BooleanListener>();
	private List<Window> visibilityListeners = new ArrayList<Window>();

	private ConnectorInterface connector;
	
	public void setConnector(ConnectorInterface connector) {
		this.connector = connector;
	}
	
	public void addMouseActiveListener(BooleanListener listener) {
		mouseActiveListeners.add(listener);
	}

	public void removeMouseActiveListener(BooleanListener listener) {
		mouseActiveListeners.remove(listener);
	}
	
	public void addVisibilityListener(Window listener) {
		visibilityListeners.add(listener);
	}

	public void removeVisibilityListener(Window listener) {
		visibilityListeners.remove(listener);
	}
	
	@Override
	public void keyPressed(KeyEvent ke) {
//		System.out.println(ke);
//		System.out.println(ke.isControlDown());
		
		if (ke.isControlDown()) {
			switch (ke.getKeyCode()) {
			case 73: //'i'
				changeVisibility();
				break;
			case 65: //'a'
				if (connector != null && !connector.isConnected()) {
					connector.connect();
				}
				enableMouseActivation();
				break;
			case 68: //'d'
				disableMouseActivation();
				if(ke.isShiftDown()) {
					connector.disconnect(); //also stop connection to track data feed
				}
				break;
			default:
				break;
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {}

	@Override
	public void keyTyped(KeyEvent arg0) {}
	
	private void enableMouseActivation() {
		for(BooleanListener listener : mouseActiveListeners) {
			listener.setActive(true);
			//System.out.println("mouse panel says active=" + true);
		}
	}
	
	private void disableMouseActivation() {
		for(BooleanListener listener : mouseActiveListeners) {
			listener.setActive(false);
			//System.out.println("mouse panel says active=" + false);
		}
	}

	private void changeVisibility() {
		appVisible = !appVisible;
		for(Window listener : visibilityListeners) {
			listener.setVisible(appVisible);
			//System.out.println("key controller says visible=" + appVisible);
		}
	}
}
